<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="900px"
    @close="close"
  >
    <el-form
      ref="form"
      label-width="128px"
      :model="formData"
      :rules="rules"
      size="medium"
    >
      <el-form-item label="分类" prop="cat">
        <el-select
          v-model="formData.cat"
          class="el-intelirri"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in cats"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" clearable placeholder="名称" />
      </el-form-item>
      <el-form-item label="血液成分码" prop="code">
        <el-input v-model="formData.code" clearable placeholder="血液成分码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit('mainForm')">提交</el-button>
        <el-button @click="reset('mainForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  import { updateOne as doEdit, addOne as doAdd } from '@/api/bloodCode'
  import { removeEmptyField } from '@/utils'
  export default {
    data() {
      return {
        formData: {
          cat: '',
          name: '',
          code: '',
        },
        rules: {
          cat: [{ required: true, trigger: 'blur', message: '分类必须' }],
          name: [{ required: true, trigger: 'blur', message: '名称必须' }],
          code: [
            { required: true, trigger: 'blur', message: '血液成分码必须' },
          ],
        },
        title: '',
        cats: ['红细胞', '血小板', '血浆', '全血', '冷沉淀'],
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.formData = Object.assign({}, row)
        }
        this.dialogVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.formData = {
          cat: '',
          name: '',
          code: '',
        }
        this.dialogVisible = false
      },
      submit() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.title === '编辑') {
              let { msg } = await doEdit(
                this.formData.id,
                removeEmptyField(this.formData)
              )
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            } else {
              let { msg } = await doAdd(removeEmptyField(this.formData))
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            }
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
